<?php
namespace app\api\controller;
use think\Loader;
use think\Config;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;
use think\Log;
/**工具**/
use redis\Redis;

class Task extends Command
{
    /**
     * 定时任务
     * Author GNLEON
     * @var string
     */
    private $view_tbale = 'view_wx_tmplate_message';
    private $table = 'wx_tmplate_message';
    protected function configure()
    {
        $this->setName('task')
            ->setDescription('定时计划：每天生成一个日期文件');
    }

    protected function execute(Input $input, Output $output)
    {
        $output->writeln('send by user with appointment...'.date("Y-m-d H:i:i",time()));
        /*** 这里写计划任务列表集 START ***/
        //查微信定时签到退
        $this->sendtest();
        //隔天过期访问邀请
        $nowtime = time();
        $start_arr = [strtotime('23:59:00'),strtotime('12:00:00'),strtotime('17:59:00')];
        $end_arr = [strtotime('23:59:59'),strtotime('12:00:59'),strtotime('17:59:59')];
        //检查过期邀请
        if($nowtime >= $start_arr[0] && $nowtime <= $end_arr[0]){
            $this->check_appointment();
        }
        //检查过期会员
        // if($nowtime >= $start_arr[1] && $nowtime <= $end_arr[1]){
        //     $this->check_is_member();
        // }
        //门卫定时推送列表-设定状态
        if($nowtime >= $start_arr[2] && $nowtime <= $end_arr[2]){
            $this->check_app_with_security();
        }
        //提前推送消息预约邀请| 1小时差值|(每分钟处理)
        $this->apphour_send();
        /*** 这里写计划任务列表集 END ***/
        $output->writeln('appointment send End...'.date("Y-m-d H:i:s",time()));
        
    }   
    /**
     * 邀请预约提前提醒
     * @HtttpRequest                              get|post
     * @Author       GNLEON
     * @Param
     * @DateTime     2020-12-01T08:55:49+0800
     * @LastTime     2020-12-01T08:55:49+0800
     * @return       [type]                       [description]
     * @remark
     *           redis keys     dev_hour_appointment_issend
     *           1小时左右 58 59 60分钟 redis控制重复发送       
     */
    public function apphour_send(){
        Loader::import('Wechat_OA', EXTEND_PATH);
        $wechatOA = new \Wechat_OA();
        
        $redis = new Redis();

        $table_list = Db::table('view_new_app_meeting_info_copy_date')->where('cur_visittime between  0.98 and 1 ')->select();

        //生成数据的id list
        $now_id_list = array_column($table_list, "id");
        //获取已发送
        $redis_list = $redis::get("dev_hour_appointment_issend");

        if($redis_list){

            $app_id_list = explode(",", $redis_list);
            //生成相同的id arr
            $cur_id_list = array_intersect($app_id_list,$now_id_list);
            //将相同的id arr 去除
            $send_id_list =  array_diff($now_id_list,$cur_id_list);
            //放回redis(定时删除keys中的隔天值)
            foreach ($send_id_list as $key => $value) {
                # code...
                array_push($app_id_list, $value);
            }

            $back_keys = implode(",",$app_id_list);
            $result = $redis::set("dev_hour_appointment_issend",$back_keys);

        }else{
            $send_id_list = $now_id_list;
            //放回redis
            $back_keys = implode(",", $send_id_list);
            $result = $redis::set("dev_hour_appointment_issend",$back_keys);
        }
        //end id 处理

        /*发送消息
            待优化 循环(一次性发送所有)
            lasttime:2020年12月1日10:59
        */
        foreach ($send_id_list as $key => $value) {
            # code...
            $finddata = Db::table('view_new_app_meeting_info_copy_date')->where('id = '.$value)->find();
            if(!$finddata){continue;}
            if($finddata['type']==1){
                $send_tips = [
                    'title' => '邀请通知',
                    'key1' => '邀请',
                    'url_app' => "http://devs.zsicp.com/h5/#/pages/yaoqing/xiangqing?detailDate=",
                    'url_vister' => "http://devs.zsicp.com/h5/#/pages/yaoqing/xiangqing?detailDate=",
                ];

            }
            if($finddata['type']==2){
                $send_tips = [
                    'title' => '预约通知',
                    'key1' => '预约',
                    'url_app' => "http://devs.zsicp.com/h5/#/pages/comster/comster",
                    'url_vister' => "http://devs.zsicp.com/h5/#/pages/myyuyue/appointmentDetails?appinfo=",
                ];
            }
            //end tips
            //发送受访人
            if($finddata['app_uid']){
                $app_info = Db::table('view_user')->where('id = '.$finddata['app_uid'])->find();

                $data = [
                    'template_id' => 'Exkadv3HIt-2WQtMdfi3hFMwZmLl1eTZRXNj8SV4bwI',
                    'array' => [
                        'first' => "(订阅消息)-{$send_tips['title']}",
                        'keyword1' => "您的最新{$send_tips['key1']}",
                        'keyword2' => $app_info['name'],
                        'keyword3' => date("Y-m-d H:i",$finddata['app_visittime']),
                        'remark' => "点击查看该{$send_tips['key1']}详情,(如已处理,请忽略本消息)",
                    ],
            
                ];
                //处理url
                $url = '';
                if($finddata['type']==1){
                    $url = $url.$send_tips['url_app']."{'id':".$finddata['id']."}";
                }elseif ($finddata['type']==2) {
                    //待定到详情
                    $url = $url.$send_tips['url_app'];
                }
                $sendRes = $wechatOA->send_WXtpl($app_info['openid'],$data,$url);
                //$sendRes = $wechatOA->send_WXtpl("ox8satwQkcC8KNFz4RBWneEdPQj4",$data,$url);
            }
            //end app
            //发送访客
            if($finddata['vister_uid']){
                $vister_info = Db::table('view_user')->where('id = '.$finddata['vister_uid'])->find();

                $data = [
                    'template_id' => 'Exkadv3HIt-2WQtMdfi3hFMwZmLl1eTZRXNj8SV4bwI',
                    'array' => [
                        'first' => "(订阅消息)-{$send_tips['title']}",
                        'keyword1' => "您的最新{$send_tips['key1']}",
                        'keyword2' => $vister_info['name'],
                        'keyword3' => date("Y-m-d",$finddata['app_visittime']),
                        'remark' => "点击查看该{$send_tips['key1']}详情,(如已处理,请忽略本消息)",
                    ],
            
                ];
                //处理url
                $url = '';
                if($finddata['type']==1){
                    $url = $url.$send_tips['url_vister']."{'id':".$finddata['id']."}";
                }elseif ($finddata['type']==2) {
                    $url_data = Db::table('view_new_app_meeting_info')->where('vister_uid = '.$vister_info['id'].' and appointmentid = '.$finddata['id'])->find();
                    $url = $url.$send_tips['url_vister'].json_encode($url_data);
                    
                }
                $sendRes = $wechatOA->send_WXtpl($vister_info['openid'],$data,$url);
                //$sendRes = $wechatOA->send_WXtpl("ox8satwQkcC8KNFz4RBWneEdPQj4",$data,$url);
                
            }
            //end fk
        }
    }

    /**
     * [发送未设状态的邀请预约状态]
     * @HtttpRequest                              get|post
     * @Author       GNLEON
     * @Param
     * @DateTime     2020-11-13T17:51:55+0800
     * @LastTime     2020-11-13T17:51:55+0800
     * @return       [type]                       [description]
     */
    public function check_app_with_security(){
        Loader::import('Wechat_OA', EXTEND_PATH);
        $wechatOA = new \Wechat_OA();
        $find_all = Db::table('view_new_app_meeting_info')->where('security_uid is not null and arrive_status != 4 and appointment_status = 0')
                                                          ->where('app_visittime','between',[strtotime(date('Ymd')),strtotime(date('Ymd'))+ 86400])
                                                          ->select();
        if(!$find_all){exit();}
        $appid = array_column($find_all, 'id');
        $security_uid_arr = array_column($find_all,'security_uid');
        $security_uid = array_flip($security_uid_arr);
        $security_uid = array_flip($security_uid);

        //分配uid
        //分配app id
        //发送----------
        foreach ($security_uid as $key => $value) {
            $appointment_list = Db::table('view_new_app_meeting_info')->where('security_uid = '.$value.' and arrive_status != 4 and appointment_status = 0')
                                                          ->where('app_visittime','between',[strtotime(date('Ymd')),strtotime(date('Ymd'))+ 86400])
                                                          ->select();
            $security_info = Db::table('view_user')->where('id = '.$value)->find();
            # code...
            // 客户需求：{{keyword1.DATA}}
            // 客户名称：{{keyword2.DATA}}
            // 提出时间：{{keyword3.DATA}}
            // {{remark.DATA}}"
            $data = [
                'template_id' => 'Exkadv3HIt-2WQtMdfi3hFMwZmLl1eTZRXNj8SV4bwI',
                'array' => [
                    'first' => "(订阅消息)-",
                    'keyword1' => "你好,请处理未完成的访客状态",
                    'keyword2' => "-{$security_info["name"]}-",
                    'keyword3' => date("Y-m-d",time()),
                    'remark' => '如已处理,请忽略本消息'
                ],
        
            ];
            $url = 'http://devs.zsicp.com/h5/#/pages/yuyuejilu/yuyuejilu';
            $sendRes = $wechatOA->send_WXtpl($security_info['openid'],$data,$url);
        }

    }

    //检查隔天所有邀请
    //@remark 
    /**
     * * 待修改为
     * app_status 0未完成(arrive_status 0,1,2,3,6) 
     * 
     * app_status 1已完成(arrive_status 4 5 )  
     * 
     * app_status 2已逾期(app_status 0 ,,,arrive_status ==0 meeting_status无论什么状态) 
     * 
     * app_status 3逾期完成(app_status 0，arrive_status !=0 meeting_status无论什么状态)
     * 
     * @Author       GNLEON
     * @Param
     * @DateTime     2020-11-06T11:14:04+0800
     * @LastTime     2020-11-06T11:14:04+0800
     * @return       [type]                       [description]
     */
    public function check_appointment(){
        //$where = 'app_visittime >= '.strtotime('00:00:00').' and  app_visittime <= '.strtotime('23:59.59').' and arrive_status not in (4,5)';
        $where_status2 = 'app_visittime < '.time().' and arrive_status = 0 and status not in (1,2,3)';
        $where_status3 = 'app_visittime < '.time().' and arrive_status in (1,2,3,6) and status not in (1,2,3)';
        $res_status2 = Db::table('view_new_app_meeting_info_copy')->where($where_status2)->select();
        $res_status3 = Db::table('view_new_app_meeting_info_copy')->where($where_status3)->select();
        $appointment_ids_status2 = array_column($res_status2, 'id');
        $appointment_ids_status3 = array_column($res_status3, 'id');
        //$arrive_id = array_column($res, 'arrive_id');
        try{
            //逾期
            $data = [
                'auditing' => 1,
                'status' => 2

            ];
            Db::table('appointment')->where('id','in',$appointment_ids_status2)->data($data)->update();
            //逾期完成
            $data = [
                'auditing' => 1,
                'status' => 3

            ];
            Db::table('appointment')->where('id','in',$appointment_ids_status3)->data($data)->update();
            // if($arrive_id){ 
            //     $data = [
            //         'status' => 4
            //     ];
            //     Db::table('arrive')->where('id','in',$arrive_id)->data($data)->update();
            // }
            Log::info("完成更新过时数据");
        }catch(\Throwable $th){ 
            Log::info("更新过时数据失败");
        }

        #code....   
    }

    /**
     * 检查会员过期
     * @HtttpRequest                              get|post
     * @Author       GNLEON
     * @Param
     * @DateTime     2020-11-12T14:05:12+0800
     * @LastTime     2020-11-12T14:05:12+0800
     * @return       [type]                       [description]
     */
    public function check_is_member(){
        Loader::import('Wechat_OA', EXTEND_PATH);
        $wechatOA = new \Wechat_OA();
        $table = 'store_member';

        $res = Db::table('view_store_member')->where('vip_date <= "'.date('Y-m-d',time()).'" and vip_level in (0,3)')->select();

        foreach ($res as $key => $value) {
            # code...
            $data = [
                'template_id' => '_Om5X-F675FlAPf5ceRRjA95SXWbpL0KGLDWR1Hzd_I',
                'array' => [
                    'first' => "(订阅:)你好,{$value["company_name"]} -".date("Y年m月",time())."缴费账单已生成",
                    'keyword1' => $value['money'],
                    'keyword2' => $value['vip_date'].'之前请您及时缴费',
                    'remark' => '缴费提醒'
                ],
        
            ];
            $url = '';
            $sendRes = $wechatOA->send_WXtpl($value['openid'],$data,$url);
        }


    }
    //查询需要发送的用户
    public function sendtest()
    {
        Loader::import('Wechat_OA', EXTEND_PATH);
        $wechatOA = new \Wechat_OA();
        $url = '';
        /*check*/
         //当天开始时间
        $start_time=strtotime(date("Y-m-d",time()));
        //当天结束之间
        $end_time=$start_time+60*60*24;
        $where = ' status = 2 and passtime is not null and deletetime is null';
        // $result = $this->select($this->view_tbale, $where, $field = '*', $offset = 0, $length = 1000, $order = null);
        $result = Db::name($this->view_tbale)
                    ->where($where)
                    ->field($field='*')
                    ->limit($offset=0, $length=1000)
                    ->order($order=null)
                    ->select();
        if(count($result) == 0){return;}

        foreach ($result as $key => $value) {
            if($value['deptid'] != NULL && $value['companyid'] != NULL){
                $url = 'http://devs.zsicp.com/h5/#/pages/qrcode/departmentqrcode?companyid='.$value['companyid'].'&deptid='.$value['deptid'];
            }
            # code...
            if($value['expiretime']<time()){

                $where = 'id = '.$value['id'];
                $data = [
                    'deletetime' => time()
                ];
                // $res = $this->update($this->table, $where, $data);
                $res = Db::name($this->table)
                    ->where($where)
                    ->data($data)
                    ->update();
                $data = [
                    'title'=>'到达部门扫码通知',
                    'openid'=>$value['openid'],
                    'name'=>$value['name'],
                    'mobile'=>$value['mobile'],
                    'visittime'=>date('Y-m-d H:i:s',time()),
                    'status'=>'如果您已到达部门请记得扫码',
                    'remark'=>"点击进入签到达(已签到请忽略本消息)",
                    'url'=>$url
                ];
                $result = $wechatOA->send_message($data);
            }
            /*防--
                丢弃*/
            // if($value['expiretime']>time() && $value['deletetime'] == NULL){
            //     $where = 'id = '.$value['id'];
            //     $data = [
            //         'deletetime' => time()
            //     ];
            //     $res = Db::name($this->table)
            //         ->where($where)
            //         ->data($data)
            //         ->update();
            // }
           
            
        }
        // $data = ['title'=>'到达部门扫码通知',
        //          'openid'=>$u_visterInfo['openid'],
        //         'name'=>$u_visterInfo['name'],
        //         'mobile'=>$u_visterInfo['mobile'],
        //         'visittime'=>date('Y-m-d H:i:s',$appointmentData['app_visittime']),
        //         'status'=>'如果您已到达部门请记得扫码!',
        //         'remark'=>"您已达部门，请扫码.",
        //         'url'=>''
        // ];
       
    }

}